<?php


namespace app\admin\controller\auth;

use app\admin\controller\Base;

use app\common\model\AdminRole;
use app\common\model\MenuModel as models;
use app\common\traites\PublicCrudTrait;
use think\exception\ValidateException;
use \app\validate\Menu as MenuV;


class Menu extends Base
{
    protected $model;
    use PublicCrudTrait;

    /**
     * 菜单控制器
     */
    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 菜单栏目树
     */
    public function index()
    {
        //这里查询用户可访问权限节点查询
        $admin = session('admin_user');
        if(empty($admin)) return $this->failed('请登录');
        $role = AdminRole::where('id', $admin['role'])->find();
        !empty($role) && $role= $role->toArray();

        if ($role['status'] != 1) return $this->failed('该角色被禁用');

        if ($admin['role'] == 1) {
            $list = $this->vip_menu($admin);//超级管理员
        } else {
            $list = $this->select_menu($admin);
        }

        //处理栏目树
        return $this->success($list);
    }

    public function vip_menu($admin)
    {
        //查询可访问的菜单
        $list = $this->model->where(['pid' => 0, 'status' => 1])->order('sort asc')->paginate()->each(function ($item, $key) {
            $item->children = $this->model->where(['pid' => $item['id'], 'status' => 1])->select();
        });
        return $list;
    }


    public function select_menu($admin)
    {
        //查询可访问的菜单
        $menu = \app\common\model\RoleMenu::where('role_id', $admin['role'])->find();
        if (empty($menu)) return [];
        $list = $this->model->where(['pid' => 0, 'status' => 1])->whereIn('id', $menu['auth_ids'])->order('sort asc')->paginate()->each(function ($item, $key) use ($menu) {
            $item->children = $this->model->where(['pid' => $item['id'], 'status' => 1])->whereIn('id', $menu['auth_ids'])->select();
        });
        return $list;
    }

    public function lists()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件

        $list = $this->model->order('pid desc')
            ->where(['pid'=>0])
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->each(function ($item, $key) {
            $menu = $this->model->menu;
            $item->menus = isset($menu[$item->pid]) ? $menu[$item->pid] : '顶级菜单';
            //查询下一级
            $item->children = $this->model->where(['pid' => $item['id'], 'status' => 1])->select();
        });

        return $this->success($list);
    }

    /**
     * 菜单添加
     */
    public function add()
    {
        //过滤数据
        $postField = 'pid,title,status,path,icon';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(MenuV::class)->scene('add')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        //验证成功，查询是否存在该用户
        $user = $this->model->where('title', $post['title'])->find();
        if ($user) return $this->failed('该菜单以存在');

        $post['status'] = isset($post['status']) ? $post['status'] : 1;

        $post['admin_uid'] = session('admin_user.id');
        $save = $this->model->save($post);
        if ($save) return $this->success([]);
        return $this->failed('新增失败');
    }

    /**
     * 菜单查询
     * @return mixed
     */
    public function detail()
    {
        //过滤数据
        $postField = 'id';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //验证数据
        try {
            validate(MenuV::class)->scene('detail')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //查询用户数据
        $user = $this->model->find($post['id']);
        if ($user) return $this->success($user);
        return $this->failed('菜单不存在');
    }

    /**
     * 菜单修改
     * @return mixed
     */
    public function edit()
    {
        //过滤数据
        $postField = 'id,pid,title,status,path,icon';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(MenuV::class)->scene('edit')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        //查询是否重复的该菜单
        $find = $this->model->where('title', $post['title'])->where('id', '<>', $post['id'])->find();
        if ($find) return $this->failed('该菜单以存在');

        $post['admin_uid'] = session('admin_user.id');
        //执行修改数据
        $save = $this->model->update($post);
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
}